<?php

namespace Home\Model;
use Think\Model;

/**
 * 
 */
class AccountModel extends Model
{
	/**
	 * 账户资金变动添加流水
	 * @param [type] $data [description]
	 */
	public function addAccount($data){
		return $this -> add($data);
	}

	//账户明细
	public function account($uid,$action,$record){
		$where['uid'] = $uid;
		$where['status'] = 1;
		if (is_numeric($action)) {
			$where['action'] = $action;
		}
		if (is_numeric($record)) {
			$where['record'] = $record;
		}
		return $this -> where($where) -> order('create_time desc') -> select();
	}

	/**
	 * 修改条目状态
	 * @param  [int] $id  [条目id]
	 * @param  [int] $val  [值]
	 * @param  [string] $flag [字段名称]
	 * @return [type]       [description]
	 */
	public function edit($id,$val,$flag){
		return $this -> where(array('id' => $id)) -> save(array($flag => $val));
	}
	/**
	 * 记录行为
	 * $uid   代表自己
	 * $cid   代表教师
	 * $teach 教师收到的钱
	 * $econ  平台收到的钱
	 * $salary 总的钱数
	 */
	public function addAccounts($uid,$cid,$teach,$econ,$salary){
		$m=D('Account');
		$m->startTrans();//开启事物
		//添加学生数据
		$arr = array(
			'uid'      	  => $uid,
			'change'      => $salary,
			'action'  	  => 1,
			'obj'     	  => $cid,
			'create_time' => time()
			);
		$data   = $m ->add($arr);
		//添加老师数据
		$brr = array(
			'uid'      	  => $cid,
			'change'      => $salary,
			'action'  	  => 2,
			'obj'     	  => $uid,
			'create_time' => time()
			);
		$data1  = $m ->add($brr);
		//添加平台收入
		$crr = array(
			'uid'      	  => 0,
			'change'      => $econ,
			'action'  	  => 2,
			'obj'     	  => $cid,
			'create_time' => time()
			);
		$data2  = $m ->add($crr);
		//添加教师给平台
		$drr = array(
			'uid'      	  => $cid,
			'change'      => $econ,
			'action'  	  => 1,
			'obj'     	  => 0,
			'create_time' => time()
			);
		$data2  = $m ->add($drr);
		if($arr && $brr && $crr && $drr){
			$m->commit();//成功则提交
			return true;
		}else{
			$m->rollback();//不成功，则回滚
			return false;
		}
	}
	/**
	 * 查找会员信息
	 */
	public function userInfo($id){
		return D('UserMember') ->field('nickname,logo') ->where(array('id' =>$id)) ->find();
	}
	/**
	 * 退订加流水
	 */
	public function tuiding($id,$cid,$stuSalary){
		//添加学生数据
		$arr = array(
			'uid'      	  => $id,
			'change'      => $stuSalary,
			'action'  	  => 4,
			'obj'     	  => 0,
			'create_time' => time()
			);
		//添加平台数据
		$brr = array(
			'uid'      	  => 0,
			'change'      => $stuSalary,
			'action'  	  => 1,
			'obj'     	  => $id,
			'create_time' => time()
			);
		$data1 = $this ->add($arr);
		$data2 = $this ->add($brr);
		return $data1&&$data2;
		}
}